package newkfp;

import newkfp.Item;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;
import newkfp.ItemFacade;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "itemController")
@SessionScoped
public class ItemController implements Serializable {
private List<Item> listItems;
    Loger loger;
    @EJB
    private newkfp.LogFacade logFacade;
    private Item current;
    private DataModel items = null;
    @EJB
    private newkfp.ItemFacade ejbFacade;
    @EJB
    private newkfp.FactoryFacade factoryFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private List<String> types;
    private int factoryid;

    public ItemController() {
        loger = new Loger(getLogFacade());
    }

    public SelectItem[] getFactoryList() {
        SelectItem[] items;
        List<Factory> factorys = factoryFacade.getFactoryOfCountryById(current.getCountryID());
        items = new SelectItem[factorys.size()];
        int i = 0;
        for (Factory x : factorys) {
            items[i++] = new SelectItem(x.getIdFactory(), x.getFactoryName());
        }
        return items;
    }

    public Item getSelected() {
        if (current == null) {
            current = new Item();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ItemFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(getFacade().count()) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }

        return pagination;
    }

    public String prepareList() {
        current = null;
      
        recreateModel();
        return "CreateItem";
    }
public String prepare() {
        current = null;
      
        recreateModel();
        return "";
    }
    public String prepareView(Item item) {
        current = item;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Item();
        selectedItemIndex = -1;
        recreateModel();
        return "CreateItem";
    }

    public String create() {
        try {
            loger = new Loger(getLogFacade());
            System.out.println("     " + current.getItemName());
            System.out.println("" + current.getFactoryID());
            System.out.println("" + current.getIdItem());
            current.setFactoryID(new Factory(factoryid));
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemCreated"));
            loger.LogerString("اضافة منتج جديد", 0);
            return prepareCreate();
        } catch (Exception e) {
            loger.LogerString("خطاء في اضافة منتج جديد", 1);
            loger.LogerString("ItemController : Create : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit(Item item) {
        current = item;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        loger = new Loger(getLogFacade());
        try {
            current.setFactoryID(new Factory(factoryid));
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemUpdated"));
            loger.LogerString(" تم تعديل منتج بنجاح", 0);
            return "View";
        } catch (Exception e) {
            loger.LogerString("خطاء في تعديل منتج", 1);
            loger.LogerString("ItemController : update : " + e.getMessage(), -1);

            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy(Item item) {
        current = item;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        current = null;
        return "CreateItem";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "CreateItem";
        }
    }

    private void performDestroy() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().remove(current);
            current = null;
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemDeleted"));
            loger.LogerString("تم حذف المنتج بنجاح", 0);
        } catch (Exception e) {
            loger.LogerString("خطاء في حذف المنتج", 1);
            loger.LogerString("ItemController : Destroy : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
//        recreateModel();
        clearSession();
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
         pagination=null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "CreateItem";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "CreateItem";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Item.class)
    public static class ItemControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ItemController controller = (ItemController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "itemController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Item) {
                Item o = (Item) object;
                return getStringKey(o.getIdItem());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ItemController.class.getName());
            }
        }
    }

    public SelectItem[] getTypes() {





        SelectItem[] items = new SelectItem[4];




        items[0] = new SelectItem(1, "لحوم");
        items[1] = new SelectItem(2, "لحوم غير ");
        items[2] = new SelectItem(3, "فراخ");
        items[3] = new SelectItem(4, "منتاجات زراعيه");
        return items;
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }

    public FactoryFacade getFactoryFacade() {
        return factoryFacade;
    }

    public void setFactoryFacade(FactoryFacade factoryFacade) {
        this.factoryFacade = factoryFacade;
    }

    public void itemListener(AjaxBehaviorEvent event) {
    }

    public int getFactoryid() {
        return factoryid;
    }

    public void setFactoryid(int factoryid) {
        this.factoryid = factoryid;
    }
    public String mapType(int i) {
        String type = "";
        switch (i) {
            case 1:
                type="لحوم";
                break;
            case 2:
                type="غير لحوم";
                break;
            case 3:
                type="فراخ";
                break;
            case 4:
                type="منتاجات زراعيه";
                break;
        }

        return type;
    }
   public void  clearSession(){
    Map m=  FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    m.remove("exporterController");   
    
m.remove("employeeController"); 
m.remove("customerController"); 
m.remove("countryController"); 
m.remove("billInformationController"); 
m.remove("inventoryStoreController"); 
m.remove("moneyController"); 
m.remove("billConfirmController"); 
m.remove("billExporterInformationController"); 
m.remove("logController"); 
//m.remove("itemController"); 

    }

    public List<Item> getListItems() {
           List<Item> listItems=(List<Item>)((javax.faces.model.DataModel)getItems()).getWrappedData();

        return listItems;
    }

    public void setListItems(List<Item> listItems) {
        this.listItems = listItems;
    }

}
